package com.yinhai.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Nickname;
import android.provider.ContactsContract.CommonDataKinds.Note;
import android.provider.ContactsContract.CommonDataKinds.Organization;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.CommonDataKinds.Website;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.text.TextUtils;
import android.util.Log;

import com.yinhai.util.AccoutTypeutils.CommonInflater;

/**
 * 管理通讯录的类
 * @author luojiang
 *
 */


public class ManagerContact {

	// 根据姓名删除联系人
	public void delContact(Context context, String name) {

		Cursor cursor = context.getContentResolver().query(Data.CONTENT_URI,
				new String[] { Data.RAW_CONTACT_ID },

				ContactsContract.Contacts.DISPLAY_NAME + "=?",
				new String[] { name }, null);

		ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

		if (cursor.moveToFirst()) {
			do {
				long Id = cursor.getLong(cursor
						.getColumnIndex(Data.RAW_CONTACT_ID));

				ops.add(ContentProviderOperation
						.newDelete(
								ContentUris.withAppendedId(
										RawContacts.CONTENT_URI, Id)).build());
				try {
					context.getContentResolver().applyBatch(
							ContactsContract.AUTHORITY, ops);
				} catch (Exception e) {
				}
			} while (cursor.moveToNext());
			cursor.close();
		}
	}

	// 根据号码删除联系人
	public static void delContactByNumber(Context context, String number) {

		Cursor cursor = context.getContentResolver().query(Data.CONTENT_URI,
				new String[] { Data.RAW_CONTACT_ID },

				ContactsContract.Contacts.Data.DATA1 + "=?",
				new String[] { number }, null);

		ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

		if (cursor.moveToFirst()) {
			do {
				long Id = cursor.getLong(cursor
						.getColumnIndex(Data.RAW_CONTACT_ID));

				ops.add(ContentProviderOperation
						.newDelete(
								ContentUris.withAppendedId(
										RawContacts.CONTENT_URI, Id)).build());
				try {
					context.getContentResolver().applyBatch(
							ContactsContract.AUTHORITY, ops);
				} catch (Exception e) {
				}
			} while (cursor.moveToNext());
			cursor.close();
		}
	}

	// 根据姓名更新联系人
	public boolean updateContact(Context context, String oldname, String name,
			String phone, String email, String website, String organization,
			String note) {
		Cursor cursor = context.getContentResolver().query(Data.CONTENT_URI,
				new String[] { Data.RAW_CONTACT_ID },

				ContactsContract.Contacts.DISPLAY_NAME + "=?",
				new String[] { oldname }, null);
		if (!cursor.moveToFirst()) {
			return false;
		}
		String id = cursor
				.getString(cursor.getColumnIndex(Data.RAW_CONTACT_ID));
		cursor.close();
		ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
		ops.add(ContentProviderOperation
				.newUpdate(ContactsContract.Data.CONTENT_URI)
				.withSelection(

						Data.RAW_CONTACT_ID + "=?" + " AND "
								+ ContactsContract.Data.MIMETYPE + " = ?"
								+ " AND " + Phone.TYPE + "=?",
						new String[] { String.valueOf(id),
								Phone.CONTENT_ITEM_TYPE,
								String.valueOf(Phone.TYPE_HOME) })
				.withValue(Phone.NUMBER, phone).build());

		// 更新email
		ops.add(ContentProviderOperation
				.newUpdate(ContactsContract.Data.CONTENT_URI)
				.withSelection(
						Data.RAW_CONTACT_ID + "=?" + " AND "
								+ ContactsContract.Data.MIMETYPE + " = ?"
								+ " AND " + Email.TYPE + "=?",
						new String[] { String.valueOf(id),
								Email.CONTENT_ITEM_TYPE,
								String.valueOf(Email.TYPE_HOME) })
				.withValue(Email.DATA, email).build());

		// 更新姓名
		ops.add(ContentProviderOperation
				.newUpdate(ContactsContract.Data.CONTENT_URI)
				.withSelection(
						Data.RAW_CONTACT_ID + "=?" + " AND "
								+ ContactsContract.Data.MIMETYPE + " = ?",
						new String[] { String.valueOf(id),
								StructuredName.CONTENT_ITEM_TYPE })
				.withValue(StructuredName.DISPLAY_NAME, name).build());

		// 更新网站
		ops.add(ContentProviderOperation
				.newUpdate(ContactsContract.Data.CONTENT_URI)
				.withSelection(
						Data.RAW_CONTACT_ID + "=?" + " AND "
								+ ContactsContract.Data.MIMETYPE + " = ?",
						new String[] { String.valueOf(id),
								Website.CONTENT_ITEM_TYPE })
				.withValue(Website.URL, website).build());

		// 更新公司
		ops.add(ContentProviderOperation
				.newUpdate(ContactsContract.Data.CONTENT_URI)
				.withSelection(
						Data.RAW_CONTACT_ID + "=?" + " AND "
								+ ContactsContract.Data.MIMETYPE + " = ?",
						new String[] { String.valueOf(id),
								Organization.CONTENT_ITEM_TYPE })
				.withValue(Organization.COMPANY, organization).build());

		// 更新note
		ops.add(ContentProviderOperation
				.newUpdate(ContactsContract.Data.CONTENT_URI)
				.withSelection(
						Data.RAW_CONTACT_ID + "=?" + " AND "
								+ ContactsContract.Data.MIMETYPE + " = ?",
						new String[] { String.valueOf(id),
								Note.CONTENT_ITEM_TYPE })
				.withValue(Note.NOTE, note).build());

		try {
			context.getContentResolver().applyBatch(ContactsContract.AUTHORITY,
					ops);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	// 根据号码更新联系人
	public static boolean updateContactByNumber(Context context, DataKind number,
			String name, DataKind phone, DataKind email, DataKind addr,DataKind im,
			String nickname,DataKind birthday,String organization, String note,DataKind group,DataKind ringtone) throws RemoteException, OperationApplicationException {
		Cursor cursor = context.getContentResolver().query(Data.CONTENT_URI,
				new String[] { Data.RAW_CONTACT_ID },
				ContactsContract.Contacts.Data.DATA1 + "=?",
				new String[] { number.getValue() }, null);
		if (!cursor.moveToFirst()) {
			Log.e("InsertContact", "updateContactByNumber");
			InsertContact(context,  name,  phone,email, im, addr,
					 organization, nickname, birthday,
					 note, group, ringtone) ;
			return false;
		}
		String id = cursor
				.getString(cursor.getColumnIndex(Data.RAW_CONTACT_ID));
		cursor.close();
		ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
		//phone
		ops.add(ContentProviderOperation
				.newUpdate(ContactsContract.Data.CONTENT_URI)
				.withSelection(
						
						Data.RAW_CONTACT_ID + "=?" + " AND "
								+ ContactsContract.Data.MIMETYPE + " = ?"
								+ " AND " + Phone.TYPE + "=?",
								new String[] { String.valueOf(id),
								Phone.CONTENT_ITEM_TYPE,
								String.valueOf(phone.getData2()) })
								.withValue(Phone.NUMBER, phone.getValue()).build());
		
		// 更新email
		ops.add(getUpdatedata(email, id));
		
		// 更新姓名
			ops.add(ContentProviderOperation
						.newUpdate(ContactsContract.Data.CONTENT_URI)
						.withSelection(
								Data.RAW_CONTACT_ID + "=?" + " AND "
										+ ContactsContract.Data.MIMETYPE + " = ?",
								new String[] { String.valueOf(id),
										StructuredName.CONTENT_ITEM_TYPE })
						.withValue(StructuredName.DISPLAY_NAME, name).build());
		
		// 更新addr
			ops.add(getUpdatedata(addr, id));
			// 更新im
			ops.add(getUpdatedata(im, id));
		//更新公司
			ops.add(ContentProviderOperation
					.newUpdate(ContactsContract.Data.CONTENT_URI)
					.withSelection(
							Data.RAW_CONTACT_ID + "=?" + " AND "
									+ ContactsContract.Data.MIMETYPE + " = ?",
							new String[] { String.valueOf(id),
									AccountMintype.ADDR })
					.withValue(StructuredName.DISPLAY_NAME, organization).build());
			//更新备注
			ops.add(ContentProviderOperation
					.newUpdate(ContactsContract.Data.CONTENT_URI)
					.withSelection(
							Data.RAW_CONTACT_ID + "=?" + " AND "
									+ ContactsContract.Data.MIMETYPE + " = ?",
							new String[] { String.valueOf(id),
									AccountMintype.BAK })
					.withValue(StructuredName.DISPLAY_NAME, note).build());
			//更新nickname
			ops.add(ContentProviderOperation
					.newUpdate(ContactsContract.Data.CONTENT_URI)
					.withSelection(
							Data.RAW_CONTACT_ID + "=?" + " AND "
									+ ContactsContract.Data.MIMETYPE + " = ?",
							new String[] { String.valueOf(id),
									Nickname.CONTENT_ITEM_TYPE })
					.withValue(StructuredName.DISPLAY_NAME, nickname).build());
			//更新生日
			ops.add(getUpdatedata(birthday, id));
			ops.add(getUpdatedata(group, id));
			ops.add(getUpdatedata(ringtone, id));
		
		
		// 更新note
		ops.add(ContentProviderOperation
				.newUpdate(ContactsContract.Data.CONTENT_URI)
				.withSelection(
						Data.RAW_CONTACT_ID + "=?" + " AND "
								+ ContactsContract.Data.MIMETYPE + " = ?",
								new String[] { String.valueOf(id),
								Note.CONTENT_ITEM_TYPE })
								.withValue(Note.NOTE, note).build());
		
		try {
			context.getContentResolver().applyBatch(ContactsContract.AUTHORITY,
					ops);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	// 根据号码更新联系人
	public static boolean updateContactByNumber(Context context,String num,String name,Map<Integer,List<DataKind>> maps) throws RemoteException, OperationApplicationException {
		Cursor cursor = context.getContentResolver().query(Data.CONTENT_URI,
				new String[] { Data.RAW_CONTACT_ID },
				ContactsContract.Contacts.Data.DATA1 + "=?",
				new String[] { num }, null);
		if (!cursor.moveToFirst()) {
			Log.e("InsertContact", "updateContactByNumber");
			InsertContact(context,  name, maps) ;
			return false;
		}
		String id = cursor
				.getString(cursor.getColumnIndex(Data.RAW_CONTACT_ID));
		cursor.close();
		ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
		// 更新姓名
				ops.add(ContentProviderOperation
						.newUpdate(ContactsContract.Data.CONTENT_URI)
						.withSelection(
								Data.RAW_CONTACT_ID + "=?" + " AND "
										+ ContactsContract.Data.MIMETYPE + " = ?",
										new String[] { String.valueOf(id),
										StructuredName.CONTENT_ITEM_TYPE })
										.withValue(StructuredName.DISPLAY_NAME, name).build());
		//phone
		for (int i = 0; i < AccountBean.MAXMAPSIZE; i++) {
			List<DataKind> lists = maps.get(i);
			switch(i){
			//phone
		case AccountBean.A_PHONE:
			
			//email
		case AccountBean.A_EMAIL:
			
			//im
		case AccountBean.A_IM:
			
			//addr
		case AccountBean.A_ADDR:
			//birthday
		case AccountBean.A_BIRTHDAY:
			addUpdateType(id, ops, lists);
			break;
			//orgnize
		case AccountBean.A_ORGNIZATION:
			//nickname
		case AccountBean.A_NICKNAME:
			//bak
		case AccountBean.A_NOTE:
			if(lists!=null&&!lists.isEmpty()){
			for (int j = 0; j < lists.size(); j++) {
				ops.add(ContentProviderOperation
						.newUpdate(ContactsContract.Data.CONTENT_URI)
						.withSelection(
								Data.RAW_CONTACT_ID + "=?" + " AND "
										+ ContactsContract.Data.MIMETYPE + " = ?",
										new String[] { String.valueOf(id),
										String.valueOf(lists.get(j).getMintype()) })
										.withValue(StructuredName.DISPLAY_NAME, lists.get(j).getValue()).build());
			}
			}
			break;
		case AccountBean.A_GROUP:
			if(lists!=null&&!lists.isEmpty()){
				for (int j = 0; j < lists.size(); j++) {
					ops.add(ContentProviderOperation
							.newUpdate(ContactsContract.Data.CONTENT_URI)
							.withSelection(
									Data.RAW_CONTACT_ID + "=?" + " AND "
											+ ContactsContract.Data.MIMETYPE + " = ?",
											new String[] { String.valueOf(id),
											String.valueOf(lists.get(j).getMintype()) })
											.withValue(StructuredName.DISPLAY_NAME, lists.get(j).getData2()).build());
				}
			}
			break;
		default:
			break;
		}
		}
		try {
			context.getContentResolver().applyBatch(ContactsContract.AUTHORITY,
					ops);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	private static void addUpdateType(String id,
			ArrayList<ContentProviderOperation> ops, List<DataKind> lists) {
		for (int j = 0; j < lists.size(); j++) {
			ops.add(ContentProviderOperation
					.newUpdate(ContactsContract.Data.CONTENT_URI)
					.withSelection(
							
							Data.RAW_CONTACT_ID + "=?" + " AND "
									+ ContactsContract.Data.MIMETYPE + " = ?"
									+ " AND " + Phone.TYPE + "=?",
									new String[] { String.valueOf(id),
									String.valueOf(lists.get(j).getData2()),
									lists.get(j).getMintype()})
									.withValue(Phone.NUMBER,lists.get(j).getValue() ).build());
			
			// 更新email
		}
	}

	private static ContentProviderOperation getUpdatedata(DataKind email, String id) {
		if(email!=null){
		return ContentProviderOperation
				.newUpdate(ContactsContract.Data.CONTENT_URI)
				.withSelection(
						Data.RAW_CONTACT_ID + "=?" + " AND "
								+ ContactsContract.Data.MIMETYPE + " = ?"
								+ " AND " + Email.TYPE + "=?",
								new String[] { String.valueOf(id),
								email.getMintype(),
								String.valueOf(email.getData2()) })
								.withValue(Email.DATA, email.getValue()).build();
		}else{
			return null;
		}
	}

	// 添加联系人事物
	public static void InsertContact(Context context, String name, DataKind phone,DataKind email,DataKind im,DataKind addr,
			String company,String nickname,DataKind birthday,
			String bak,DataKind group,DataKind ringtone) 
					throws RemoteException, OperationApplicationException {
		 
	      Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
	      ContentResolver resolver = context.getContentResolver();
	      ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
	      ContentProviderOperation op1 = ContentProviderOperation.newInsert(uri)
	          .withValue("account_name", null)
	          .build();
	      operations.add(op1);
	      
	      uri = Uri.parse("content://com.android.contacts/data");
	      ContentProviderOperation op2 = ContentProviderOperation.newInsert(uri)
	          .withValueBackReference("raw_contact_id", 0)
	          .withValue("mimetype", "vnd.android.cursor.item/name")
	          .withValue("data2", name)
	          .build();
	      operations.add(op2);
	      //phone
	      ContentProviderOperation op3 = getTypedata(phone, uri);
	      if(op3!=null){
		  operations.add(op3);
	      }
	      //phone
	      ContentProviderOperation opemail = getTypedata(phone, uri);
	      if(opemail!=null){
	    	  operations.add(opemail);
	      }
	      //im
	      ContentProviderOperation op4 = getTypedata(im, uri);
	      if(op4!=null){
			  operations.add(op4);
		      }
	      
	  //addr
	  ContentProviderOperation op5 = getTypedata(addr, uri);
	  if(op5!=null){
		  operations.add(op5);
	      }
	  
	  //comany
	  ContentProviderOperation op6 = ContentProviderOperation.newInsert(uri)
	          .withValueBackReference("raw_contact_id", 0)
	          .withValue("mimetype", AccountMintype.organization)
	          .withValue("data2", company)
	          .build();
	      operations.add(op6);
	  
	  //nickname
	  ContentProviderOperation op7 = ContentProviderOperation.newInsert(uri)
	          .withValueBackReference("raw_contact_id", 0)
	          .withValue("mimetype", AccountMintype.nickname)
	          .withValue("data2", nickname)
	          .build();
	      operations.add(op7);
	  //birthday
	  ContentProviderOperation op8 = getTypedata(birthday, uri);
		 if(op8!=null){
		  operations.add(op8);
		}
	  //bak
      ContentProviderOperation op9 = ContentProviderOperation.newInsert(uri)
	          .withValueBackReference("raw_contact_id", 0)
	          .withValue("mimetype", AccountMintype.BAK)
	          .withValue("data2", bak)
	          .build();
	      operations.add(op9);
	      //group
		  ContentProviderOperation op10 = getTypedata(group, uri);
		  if(op10!=null){
		  operations.add(op10);
		  }
		  //ringtone
		  ContentProviderOperation op11 = getTypedata(ringtone, uri);
		 if(op11!=null){
		  operations.add(op11);
		 }
		  
	  
	      resolver.applyBatch("com.android.contacts", operations);
	}
	public static void InsertContact(Context context,String name,Map<Integer,List<DataKind>> maps) 
					throws RemoteException, OperationApplicationException {
		
		Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
		ContentResolver resolver = context.getContentResolver();
		ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
		ContentProviderOperation op1 = ContentProviderOperation.newInsert(uri)
				.withValue("account_name", null)
				.build();
		operations.add(op1);
		
		uri = Uri.parse("content://com.android.contacts/data");
		ContentProviderOperation op2 = ContentProviderOperation.newInsert(uri)
				.withValueBackReference("raw_contact_id", 0)
				.withValue("mimetype", AccountMintype.NAME)
				.withValue("data2", name)
				.build();
		operations.add(op2);
		
		for (int i = 0; i < AccountBean.MAXMAPSIZE; i++) {
			List<DataKind> list = maps.get(i);
			switch (i) {
			case 0:
				if(list!=null&&!list.isEmpty()){
					for (int j = 0; j < list.size(); j++) {
						ContentProviderOperation cpo = getTypedata(list.get(j), uri);
						if(cpo!=null){
							operations.add(cpo);
						}
					}	
				}
			//phone
			case AccountBean.A_PHONE:
				
				//email
			case AccountBean.A_EMAIL:
				
				//im
			case AccountBean.A_IM:
				
				//addr
			case AccountBean.A_ADDR:
				//birthday
			case AccountBean.A_BIRTHDAY:
				if(list!=null&&!list.isEmpty()){
				for (int j = 0; j < list.size(); j++) {
					ContentProviderOperation cpo = getTypedata(list.get(j), uri);
					if(cpo!=null){
						operations.add(cpo);
					}
				}	
				}
				break;
				//orgnize
			case AccountBean.A_ORGNIZATION:
				//nickname
			case AccountBean.A_NICKNAME:
				//bak
			case AccountBean.A_NOTE:
				if(list!=null&&!list.isEmpty()){
				for (int j = 0; j < list.size(); j++) {
					if(list!=null&&!list.isEmpty()){
					ContentProviderOperation singleop = ContentProviderOperation.newInsert(uri)
							.withValueBackReference("raw_contact_id", 0)
							.withValue("mimetype", list.get(j).getMintype())
							.withValue("data1", list.get(j).getValue())
							.withValue("data2", list.get(j).getValue())
							.build();
					operations.add(singleop);
					}
				}
				}
				break;
			case AccountBean.A_GROUP:
				if(list!=null&&!list.isEmpty()){
				for (int j = 0; j < list.size(); j++) {
					if(list!=null&&!list.isEmpty()){
						ContentProviderOperation singleop = ContentProviderOperation.newInsert(uri)
								.withValueBackReference("raw_contact_id", 0)
								.withValue("mimetype", list.get(j).getMintype())
								.withValue(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID, list.get(j).getData2())
								.build();
						operations.add(singleop);
					}
				}
				}
//			case AccountBean.A_RINGTONE:
//				if(list!=null&&!list.isEmpty()){
//					for (int j = 0; j < list.size(); j++) {
//						if(list!=null&&!list.isEmpty()){
//							ContentProviderOperation singleop = ContentProviderOperation.newInsert(uri)
//									.withValueBackReference("raw_contact_id", 0)
//									.withValue("mimetype", list.get(j).getMintype())
//									.withValue(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID, list.get(j).getValue())
//									.build();
//							operations.add(singleop);
//						}
//					}
//				}
//				break;
			default:
				break;
			}
			
		}
//		//group
//		ContentProviderOperation op10 = getTypedata(group, uri);
//		if(op10!=null){
//			operations.add(op10);
//		}
//		//ringtone
//		ContentProviderOperation op11 = getTypedata(ringtone, uri);
//		if(op11!=null){
//			operations.add(op11);
//		}
		
		
		resolver.applyBatch("com.android.contacts", operations);
	}

	private static ContentProviderOperation getTypedata(DataKind im, Uri uri) {
		if(im!=null){
		ContentProviderOperation op =	ContentProviderOperation.newInsert(uri)
	      .withValueBackReference("raw_contact_id", 0)
	      .withValue("mimetype", im.getMintype())
	      .withValue("data1", im.getValue())            
	      .withValue("data2", im.getData2())
	      .build();
		return op;
		}else{
			return null;
		}
	}
	
	
	//判断联系人是否在通讯录内
	public static boolean getContactPeople(Context context,String incomingNumber)
    {
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = null;
        
        String[] projection = new String[]
        {
            ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER
        };

        cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, 
        ContactsContract.CommonDataKinds.Phone.NUMBER + "=?", new String[]
        { incomingNumber }, "");
        if(cursor.moveToFirst()){
        	String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        	if(TextUtils.isEmpty(phoneNumber)){
        		return true;
        	}else{
        		return false;
        	}
        }
        return true;
    }
	//查询联系人接口
		public static Map<Integer, List<com.yinhai.util.DataKind>> query(Context context,String number){
			Map<Integer,List<DataKind>> maps = new HashMap<Integer, List<DataKind>>();
	    	 ContentResolver contentResolver = context.getContentResolver();
	        // String[] projection = new String[]{ContactsContract.Data.DISPLAY_NAME};
	         String[] projection = null;
	         //Cursor cursor = resolver.query(uri, new String[]{Data.DISPLAY_NAME,"mimetype", "data1", "data2"}, null, null, null);
	         Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, 
	                 ContactsContract.CommonDataKinds.Phone.NUMBER + "=?", new String[]
	                 { number }, "");
	         if (cursor.moveToFirst()) {
	        	 int idColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
	         String  name = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
	         DataKind data = new DataKind(AccountMintype.NAME,"姓名",name, 0);
	         List<DataKind> namelist = new ArrayList<DataKind>();
	         namelist.add(data);
	         maps.put(AccountBean.A_NAME, namelist);
	         String contactId = cursor.getString(idColumn);
	        // String  phone = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.));
	      // 查看该联系人有多少个电话号码。如果没有这返回值为0
				int phoneCount = cursor
						.getInt(cursor
								.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
				if (phoneCount > 0) {
					// 获得联系人的电话号码
					List<DataKind> phonelist = new ArrayList<DataKind>();
					Cursor phones = context.getContentResolver().query(
							ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
							null,
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID
									+ " =?" , new String[]{contactId}, null);
					if (phones.moveToFirst()) {
						do {
							// 遍历所有的电话号码
							String phoneNumber = phones
									.getString(phones
											.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
							String phoneType = phones
									.getString(phones
											.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
							AccoutTypeutils.PhoneActionInflater p = new AccoutTypeutils.PhoneActionInflater();
							String lable = context.getResources().getString(p.getTypeLabelResource(Integer.parseInt(phoneType)));
							DataKind datas = new DataKind(AccountMintype.PHONE,lable,phoneNumber,Integer.parseInt(phoneType));
							phonelist.add(datas);
						} while (phones.moveToNext());
					}
					maps.put(1, phonelist);
					phones.close();
				}
				
	 //         String  email =
				// 获取该联系人邮箱
				CommonInflater  emailc = new AccoutTypeutils.EmailActionInflater();

				getAllType(context,emailc,AccountBean.A_EMAIL,maps, contactId,ContactsContract.CommonDataKinds.Email.CONTENT_URI,AccountMintype.EMAIL);
//	         String  im=
				CommonInflater comim = new AccoutTypeutils.ImActionInflater();
				getTypeByID(context,comim,AccountBean.A_IM,maps, contactId,ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
				
//	         String  addr=
				CommonInflater  atpc = new AccoutTypeutils.PostalActionInflater();
				getAllType(context,atpc,AccountBean.A_ADDR,maps, contactId,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,AccountMintype.ADDR);
//	         String  comany
				getSingleTypeByID("公司",context,AccountBean.A_ORGNIZATION,maps, contactId,ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
				//nick
				
				getSingleTypeByID("昵称",context,AccountBean.A_NICKNAME,maps,contactId,ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE);
				//birth
				CommonInflater  com7 = new AccoutTypeutils.BirhdayActionInflater();
				getTypeByID(context,com7,AccountBean.A_BIRTHDAY,maps,contactId,AccountMintype.identity);
			//	getAllType(7,maps, contactId,ContactsContract.CommonDataKinds.Identity.CONTENT_URI,AccountMintype.EMAIL);
				//bak
				getSingleTypeByID("备注",context,AccountBean.A_NOTE,maps,contactId,ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE);
			//	getAllType(8,maps, contactId,ContactsContract.CommonDataKinds.Note.CONTENT_URI,AccountMintype.EMAIL);
				//group
				maps.put(AccountBean.A_GROUP, getGroup(context, number));
				//getSingleTypeByID(context,9,maps,contactId,ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE);
				//ringtone
				maps.put(AccountBean.A_RINGTONE, getRingtone(context, number));
				
	         }
	         cursor.close();
	         return maps;
		}
		
			private static List<DataKind> getRingtone(Context context, String number) {
				   String contactId = null;
				   List<DataKind> list = null;
		           Cursor pn = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID}, 
			                 ContactsContract.CommonDataKinds.Phone.NUMBER + "=?", new String[]
			                 { number }, null);
		           if(pn.moveToFirst()){
		        	   int idColumn = pn.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
		        	    contactId = pn.getString(idColumn);
		           }
		           pn.close();
		           Cursor pn1 = context.getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, new String[]{ContactsContract.Data.CUSTOM_RINGTONE}, 
			                 ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?" , new String[]
			                 { contactId }, null);
		         if(pn1.moveToFirst()){
						list = new ArrayList<DataKind>();
		        		 String id = pn1.getString(pn1.getColumnIndex(ContactsContract.Data.CUSTOM_RINGTONE));
		        		 if(!TextUtils.isEmpty(id)){
		        		 list.add(new DataKind(AccountMintype.RINGTONE,"铃声",id,Integer.parseInt(contactId)));
		        		 }
		         }
		           pn1.close();

			return list;
		}

			private static List<DataKind> getGroup(Context cotnext,String number){
				  String contactId = null;
		          List<DataKind> lists = null;
		           Cursor pn = cotnext.getContentResolver().query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID}, 
			                 ContactsContract.CommonDataKinds.Phone.NUMBER + "=?", new String[]
			                 { number }, null);
		           if(pn.moveToFirst()){
		        	   int idColumn = pn.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
		        	    contactId = pn.getString(idColumn);
		           }
		           pn.close();
		           Cursor pn1 =cotnext.getContentResolver().query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.DATA1}, 
			                 ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "='"
								+ AccountMintype.GROUP + "'", new String[]
			                 { contactId }, null);
		         if(pn1.moveToFirst()){
		        	 lists = new ArrayList<DataKind>();
		        	 do {
						
		        		 String id = pn1.getString(pn1.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.DATA1));
		        		 Cursor cursor = cotnext.getContentResolver().query(
		     					ContactsContract.Groups.CONTENT_URI, null, ContactsContract.CommonDataKinds.GroupMembership._ID + "=?", new String[]{id}, null);
		                if(cursor.moveToFirst()) {
		                	
		                	 String name = cursor.getString( cursor.getColumnIndex("title"));
		                	 lists.add(new DataKind(AccountMintype.GROUP, "分组",name, Integer.parseInt(id)));
		                }
		        		 cursor.close();
		        		 
		        		 
					} while (pn1.moveToNext());
		         }
		           pn1.close();
		           return lists;
			}
		
		
		private static void getTypeByID(Context context,CommonInflater comim, int id,Map<Integer, List<DataKind>> maps, String contactId,String mtype) {
			Cursor IMs = context.getContentResolver().query(
					ContactsContract.Data.CONTENT_URI,
					new String[] { Data._ID,ContactsContract.CommonDataKinds.Im.DATA,ContactsContract.CommonDataKinds.Im.TYPE },
					ContactsContract.Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "='"
							+ mtype + "'",
					new String[] { contactId }, null);
			 List<DataKind> imlist = new ArrayList<DataKind>();
			if (IMs.moveToFirst()) {
				do {
					String type = IMs.getString(IMs
							.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
					String date = IMs
							.getString(IMs.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
					String lable = context.getResources().getString(comim.getTypeLabelResource(Integer.parseInt(type)));
					DataKind datas = new DataKind(AccountMintype.IM,lable,date,Integer.parseInt(type));
					imlist.add(datas);	
				} while (IMs.moveToNext());
			}
			maps.put(id, imlist);
			IMs.close();
		}
		private static void getSingleTypeByID(String string, Context context,int id,Map<Integer, List<DataKind>> maps, String contactId,String mtype) {
			Cursor IMs = context.getContentResolver().query(
					ContactsContract.Data.CONTENT_URI,
					new String[] { Data._ID,ContactsContract.CommonDataKinds.Im.DATA,ContactsContract.CommonDataKinds.Im.TYPE },
					ContactsContract.Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "='"
							+ mtype + "'",
							new String[] { contactId }, null);
			List<DataKind> imlist = new ArrayList<DataKind>();
			if (IMs.moveToFirst()) {
				do {
					String date = IMs
							.getString(IMs.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
					DataKind datas = new DataKind(AccountMintype.IM,string,date,0);
					imlist.add(datas);	
				} while (IMs.moveToNext());
			}
			maps.put(id, imlist);
			IMs.close();
		}

		private static void getAllType(Context context,CommonInflater emailc, int id,Map<Integer, List<DataKind>> maps, String contactId,Uri uri,String type) {
			Cursor emails = context.getContentResolver().query(
					uri,
					null,
					ContactsContract.CommonDataKinds.Phone.CONTACT_ID
							+ " = " + contactId, null, null);
			List<DataKind> emaillist = new ArrayList<DataKind>();
			if (emails.moveToFirst()) {
				do {
					// 遍历所有的电话号码
					String emailType = emails
							.getString(emails
									.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
					String emailValue = emails
							.getString(emails
									.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
					String lable = context.getResources().getString(emailc.getTypeLabelResource(Integer.parseInt(emailType)));
					DataKind datas = new DataKind(type,lable,emailValue,Integer.parseInt(emailType));
					emaillist.add(datas);
				} while (emails.moveToNext());
			}
			maps.put(id, emaillist);
			emails.close();
		}
	
	
	/**
	 * 根据ID删除RAW_CONTACTS表中的数据
	 * @param context
	 */
	public static void deleteRawContacts(Context context,String[] rawContactIds ) {
		Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
		for(String rawContactId:rawContactIds) {
			context.getContentResolver().delete(ContentUris.withAppendedId(RawContacts.CONTENT_URI,
		                        Long.parseLong(rawContactId)), null, null);
		}
		 
	}
//	public static void deleteData(Context context,List<Integer> rawContactIds ) {
//		Uri uri = Uri.parse("content://com.android.contacts/data");
//		for(Integer rawContactId:rawContactIds) {
//			ContentValues values = new ContentValues();
//			values.put("contact_id", "");
//			values.put("deleted", "1");
//			context.getContentResolver().update(uri, values, "_id="+rawContactId, null);
//		}
//		
//	}
}
